package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;


public class SimpleRedisLock implements ILock {
    /**
     * name:业务的名字
     */
    private String name;
    private StringRedisTemplate redisTemplate;

    //防止误删锁的问题，需要创建全局唯一的KEY 前缀是ID_PREFIX
    private static final String ID_PREFIX = UUID.randomUUID(true) + "-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }

    private static final String KEY_PREFIX = "lock:";

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String id = ID_PREFIX + Thread.currentThread().getId();
        //尝试获取锁
        Boolean sussess = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, id, timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(sussess);
    }


    /**
     * 基于lua脚本解决原子性问题
     */
    @Override
    public void unLock() {
        //获取当前的线程表示
        String id = ID_PREFIX + Thread.currentThread().getId();
        redisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                id);

    }

}
//    @Override
//    public void unLock() {
//        //获取当前的线程表示
//        String id = ID_PREFIX +Thread.currentThread().getId();
//
//        //获取锁的线程标识
//        String lockId = redisTemplate.opsForValue().get(KEY_PREFIX + name);
//
//        if (id.equals(lockId)){
//            redisTemplate.delete(KEY_PREFIX + name);
//        }
//
//    }

